#include "PowerPointOOXMLFile.h"


PowerPointOOXMLFile::PowerPointOOXMLFile(string filePath)
{
	fileResult = SUCCESS;
	ReadContent(filePath);
}


PowerPointOOXMLFile::~PowerPointOOXMLFile()
{
}

std::string PowerPointOOXMLFile::ParagraphText()
{
	return _paragraphText;
}

ERRORTYPE PowerPointOOXMLFile::getResult()
{
	return fileResult;
}

void PowerPointOOXMLFile::ReadContent(string filePath)
{
#ifdef _WIN32
	wchar_t dst[MAX_PATH];
	int length = 0;
	GbkToUnicode(filePath.c_str(), nullptr, length);
	GbkToUnicode(filePath.c_str(), dst, length);
	HZIP hz = OpenZip(dst, 0);
#else

	HZIP hz = OpenZip(filePath.c_str(), 0);
#endif
	if (hz == NULL)
	{
		fileResult = FILE_OPEN_FAILED;
		return;
	}
	ZIPENTRY ze; GetZipItem(hz, -1, &ze); int numitems = ze.index;


	wchar_t txtPath[MAX_PATH];
	auto index = 1;
	while (1)
	{
		stringstream ss;
		ss << index++;
		string txtPathTemp = "ppt/slides/slide" + ss.str()+".xml";

		int length = 0;
#ifdef _WIN32
		GbkToUnicode(txtPathTemp.c_str(), nullptr, length);
		GbkToUnicode(txtPathTemp.c_str(), txtPath, length);
		int i = 0;
		ZRESULT result = FindZipItem(hz, txtPath, true, &i, &ze);
#else
		int i = 0;
		ZRESULT result = FindZipItem(hz, txtPathTemp.c_str(), true, &i, &ze);
#endif
		if (result == 0)
		{
			char *ibuf = new char[ze.unc_size];
			UnzipItem(hz, i, ibuf, ze.unc_size);

			tinyxml2::XMLDocument ppt;

			ppt.Parse(ibuf, ze.unc_size);

			
			XMLElement* root = ppt.RootElement();
			if (root == NULL)
			{
				std::cerr << "Failed to load file: No root element." << std::endl;
				ppt.Clear();
				
			}
			std::string xml_time;
			XMLElement *source_elem = NULL;
			parseBody(root, source_elem, xml_time);
			delete ibuf;
		}
		else
		{
			if (index == 2)
			{
				fileResult = FILE_NOT_PPTX;
			}
			
			break;
		}
	}

	CloseZip(hz);
	

	/*for (int zi = 0; zi < numitems; zi++)
	{
	GetZipItem(hz, zi, &ze);
	
	UnzipItem(hz, zi, ze.name);
	
	}*/

}

void PowerPointOOXMLFile::parseBody(XMLElement * rootNode, XMLElement * tempEle, string & info)
{
	for (XMLElement *nodeEle = rootNode->FirstChildElement(); nodeEle; nodeEle = nodeEle->NextSiblingElement())
	{
		tempEle = nodeEle;

		if (nodeEle->GetText() != NULL)
		{
			string tag = nodeEle->Value();
			//string content = nodeEle->GetText();
			_paragraphText.append(nodeEle->GetText());
		}
		if (!tempEle->NoChildren())
		{
			parseBody(tempEle, NULL, info);
		}
	}
}
